import React, {useState} from 'react';
import {Button, Checkbox, Form, Input, message, Space} from "antd";
import {LockOutlined, UserOutlined} from '@ant-design/icons';
import {useNavigate} from "react-router-dom";
import MD5 from 'js-md5'
import '@/views/Login/login.css'

const Login = () => {
    const [form] = Form.useForm();
    const navigator = useNavigate();
    let localStorageCheck = localStorage.getItem('isRemember') ? JSON.parse(localStorage.getItem('isRemember')) : {
        check: false,
        userName: '',
        passWord: '',
    };
    let [loginForm, setLoginForm] = useState({
        isCheck: localStorageCheck.check,
        userName: localStorageCheck.userName,
        passWord: localStorageCheck.passWord,
    });

    // 校验账号函数
    const validateFun = (_, value) => {
        if (_.fullField === 'userName') {
            if (!value) {
                return Promise.reject(new Error('用户名不能为空'));
            }
            if (!/^[a-zA-Z0-9]+$/.test(value)) {
                return Promise.reject(new Error('用户名只能包含字母和数字'));
            }
            return Promise.resolve();
        }
        if (_.fullField === 'passWord') {
            if (!value) {
                return Promise.reject(new Error('密码不能为空'));
            }
            if (!/^[a-zA-Z0-9]+$/.test(value)) {
                return Promise.reject(new Error('密码只能包含字母和数字'));
            }
            return Promise.resolve();
        }
    };

    // 校验通过函数
    const onFinish = async () => {
        if (loginForm.isCheck) {
            localStorage.setItem('isRemember', JSON.stringify({
                check: loginForm.isCheck,
                userName: loginForm.userName,
                passWord: MD5(loginForm.passWord),
            }))
        } else {
            localStorage.removeItem('isRemember')
        }
        // let {data, err} = await api.post(url, {
        //     userName: form.userName,
        //     password: MD5(form.password)
        // })
        // 处理错误
        // message.error('This is a normal message');
        navigator('/')
    }

    // 修改表单数据函数
    const onChang = (e) => {
        const {name, value, type} = e.target;
        if (type === "checkbox") {
            setLoginForm({
                ...loginForm,
                isCheck: e.target.checked,
            })
        } else {
            setLoginForm({
                ...loginForm,
                [name]: value,
            })
        }
    }

    return (
        <div className={'container'}>
            <div className={'containerBox'}>
                <img src={'https://java-admin.likeadmin.cn/adminapi/static/login_image.png'}/>
                <div className={'formBox'}>
                    <div className={'containerTitle'}>likeadmin开源</div>

                    <Form form={form} onFinish={onFinish} autoComplete="off"
                          scrollToFirstError={{block: 'start', focus: true,}}>
                        <Form.Item initialValue={loginForm.userName} rules={[{validator: validateFun}]}
                                   validateTrigger="onBlur" name="userName">
                            <Input onChange={onChang} value={loginForm.userName} size={"large"}
                                   prefix={<UserOutlined/>} name={"userName"} placeholder="请输入账号"/>
                        </Form.Item>

                        <Form.Item name="passWord" initialValue={loginForm.passWord} rules={[{validator: validateFun}]}>
                            <Input.Password onChange={onChang} value={loginForm.passWord} visibilityToggle
                                            size={"large"} prefix={<LockOutlined/>} type="password"
                                            placeholder="请输入密码" name={"passWord"}/>
                        </Form.Item>
                    </Form>

                    <div className={'rememberBox'}>
                        <Checkbox className={'checkBox'} checked={loginForm.isCheck} onChange={onChang}>
                            记住账号
                        </Checkbox>
                    </div>
                    <Button className={'btnBox'} type="primary" size="large" onClick={() => form.submit()}>登录</Button>
                </div>
            </div>
        </div>
    );
};

export default Login;